package pub.dsb.example.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * https://leetcode-cn.com/problems/print-foobar-alternately/
 * </p>
 *
 * @author Yi
 * @version V1.0.0
 * @date 2020/12/30 11:30
 * @modificationHistory=========================逻辑或功能性重大变更记录
 * @modify By: {修改人} 2020/12/30 11:30
 * @modify reason: {方法名}:{原因}
 * ...
 * @since V1.0.0
 */
public class LC1115Test {

    public static void main(String[] args) {
        int n = 2;
        FooBar fooBar = new FooBar(n);
        for (int i = 0; i < n; i++) {
            new Thread(() -> {
                try {
                    fooBar.foo();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
            new Thread(() -> {
                try {
                    fooBar.bar();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

}

/**
 * LC 1115 方式1
 */
class FooBar {

    private int n;
    private volatile int fooCount;
    private volatile int barCount;
    private ReentrantLock lock = new ReentrantLock();
    private Condition fooCondition = lock.newCondition();
    private Condition barCondition = lock.newCondition();

    public FooBar(int n) {
        this.n = n;
    }

    public void foo() throws InterruptedException {
        for (int i = 0; i < n; i++) {
            lock.lock();
            try{
                while (fooCount > barCount) {
                    fooCondition.await();
                }
                System.out.println("foo");
                fooCount+=1;
                barCondition.signalAll();
            }finally {
                lock.unlock();
            }
        }
    }

    public void bar() throws InterruptedException {
        for (int i = 0; i < n; i++) {
            lock.lock();
            try{
                while (barCount >= fooCount) {
                    barCondition.await();
                }
                System.out.println("bar");
                barCount+=1;
                fooCondition.signalAll();
            }finally {
                lock.unlock();
            }
        }
    }
}
